package com.ivens;

import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;

public class Utility {

	private static void setListViewHeightBasedOnChildren(
			ExpandableListView listView ) {
		ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;

		for (int i = 0; i < listAdapter.getGroupCount(); i++) {
			boolean expanded = false;
			View groupItem = listAdapter.getGroupView(i, expanded, null,
					listView);
			View childItem = listAdapter.getChildView(i, 0, false, null,
					listView);
			System.out.println("expanded:::" + expanded);
			groupItem.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			totalHeight += groupItem.getMeasuredHeight();
			if (expandeds!=null && expandeds[i]) {
				childItem.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
				totalHeight += childItem.getMeasuredHeight();
			}
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	public static void setListViewHeightBasedOnGroups(
			ExpandableListView listView) {
		setListViewHeightBasedOnChildren(listView);
	}
	private static boolean[] expandeds=null;
	public static void setListViewHeightBasedOnExpandedChilds(
			ExpandableListView listView,int groupPosition,boolean expanded) {
			if(expandeds==null){
				expandeds=new boolean[listView.getExpandableListAdapter().getGroupCount()];
			}
			expandeds[groupPosition]=expanded;
		setListViewHeightBasedOnChildren(listView);
	}

}